import requests
from requests import get
from django_user_agents.utils import get_user_agent



def getNetwork(request,ip):# 获取用户ip
    address = getAddress(ip)
    city = address['city'] #市
    province = address['province'] #省
    user_agent = get_user_agent(request)  # 浏览器
    if user_agent.is_mobile:
        browser_type = "手机"
    elif user_agent.is_pc:
        browser_type = "PC"
    elif user_agent.is_tablet:
        browser_type = "平板"
    else:
        browser_type = "未知"
    return {'ip': ip, 'city': city, 'province': province, 'agent': user_agent, 'browser': browser_type}


def getAddress(ip_address):  # 请求高德api
    url = 'https://restapi.amap.com/v3/ip?&output=json&key=8ea51785bbe47085299e67bab7aec1e0&ip='+ip_address
    try:
        res = requests.get(url, timeout=5)
        result = res.json()
        if result['info'] == 'OK':
            province = result['province']
            city = result['city']
        else:
            province = None
            city = None
    except TimeoutError:
         province = None
         city = None

    return {'province': province, 'city': city}
